const charset = require('superagent-charset');
const superagent = charset(require('superagent'));
const cheerio = require('cheerio');
const EventEmitter = require('events').EventEmitter;
const emitter = new EventEmitter();

superagent.get('http://www.cnedu.cn/examination/').charset('gb2312').end((error,res) => {
    if(error){
        console.log(error);
        return next(error);
    }
    const $ = cheerio.load(res.text);

    const tableList = $('.ztjs .body table');
    let list = [];
    if (tableList.length > 0) {
        tableList.each((index, item) =>{
            let yearParam = $(item).find('th').html();
            if (yearParam) {
                // console.log(UnicodeToStr(yearParam))
            }

            //超链接
            let tempUrlList = [];
            let urlList = $(item).find('td table a');
            if (urlList && urlList.length > 0) {
                urlList.each((index, item) => {
                    let lesson = UnicodeToStr($(item).html());
                    let url = $(item).attr('href');
                    if (!lesson.includes('数学')) {
                        // console.log(`${lesson} --- ${url}`);
                        tempUrlList.push(url);
                    }
                });
            }
            if (yearParam && urlList.length >0) {
                list.push({
                    name: yearParam,
                    urls: tempUrlList
                });
            }
        });
    }
    emitter.emit('HandleDetailUrl', list);
});

function UnicodeToStr(str) {
    return unescape(str.replace(/&#x/g,'%u').replace(/;/g,''));
}

emitter.on('HandleDetailUrl', HandleDetailUrl);
function HandleDetailUrl(param) {
    if (!param) {
        return;
    }
    superagent.get(param[0].urls[0]).charset('gb2312').end((error,res) => {
        if(error){
            console.log(error);
            return next(error);
        }
        const $ = cheerio.load(res.text);
        let contentList = $('#fontzoom p');
        contentList.map((index, item) => {
           console.log(UnicodeToStr($(item).html()));
        });
    });
}